package com.hh.vrserver.web;

import com.hh.vrserver.model.VrEntity;
import com.hh.vrserver.service.VrService;
import com.hh.vrserver.web.vo.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author yeweijun
 * @version 1.0 2023/7/4 18:56
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
@Slf4j
public class VrServerController {
    private final VrService vrService;

    @GetMapping("/query")
    public WebResult<VrData> query(String id) {
        return WebResult.success(vrService.query(id));
    }

    @GetMapping("/login")
    public WebResult<VrData> login(String id, String password) {
        return WebResult.success(vrService.login(id, password));
    }

    @PostMapping("/webQuery")
    public WebResult<Page<VrEntity>> webQuery(@RequestBody PageQuery pageQuery) {
        log.info("pageQuery={}", pageQuery);
        return WebResult.success(vrService.pageQuery(pageQuery));
    }

    @PostMapping("/update")
    public WebResult<String> update(@RequestBody VrDataVo vrData) {
        log.info("vrData={}", vrData);
        vrService.saveOrUpdate(vrData);
        return WebResult.success("");
    }

    @Value("${login.user}")
    private String userName;
    @Value("${login.password}")
    private String password;

    @PostMapping("/webLogin")
    public WebResult<String> webLogin(@RequestBody User user, HttpSession session) {
        if (user.getUsername().equals(userName) && user.getPassword().equals(password)) {
            session.setAttribute("u", user);
            return WebResult.success(user.getUsername());
        } else {
            throw new IllegalArgumentException("密码错误");
        }
    }

    @PostMapping("/check")
    public WebResult<String> check(HttpSession session) {
        User u = (User) session.getAttribute("u");
//        u=new User();
//        u.setUsername("12");
        if (u != null) {
            return WebResult.success(u.getUsername());
        } else {
            return WebResult.success(null);
        }
    }
}
